<template>
  <div >
    <van-nav-bar title="设备管理" left-text="返回" right-text="按钮" @click-left="sanQRCode" @click-right="addDevice">
      <van-icon name="qr" slot="left" size="1.4em" />
      <van-icon name="add" slot="right" size="1.4em" />
    </van-nav-bar>
    <div>
      <van-swipe-cell :right-width="delWidth" :on-close="onClose" v-for="(item, index) in items" :key="index">
        <van-cell-group :border="true">
          <van-cell :value="item.imei" icon="smoke-sensor2">
            <template slot="title">
              <span class="van-cell-text">{{item.devName}}</span>
              <van-tag type="danger">{{item.devModel}}</van-tag>
            </template>
          </van-cell>
        </van-cell-group>
        <van-button slot="right" class="van-swipe-cell__right" :style="{'width':delWidth+'px'}" tag="div" @click="unBindDevice(item.imei)">
          解绑
        </van-button>
      </van-swipe-cell>
    </div>

    <is-empty v-if="isEmpty">暂无设备，请添加设备</is-empty>

    <van-popup v-model="addDeviceShow" position="top" :overlay="true">
      <div style="padding:10px 30px 20px">
        <div style="text-align:center;font-size:18px;padding:10px;">绑定设备</div>
        <van-cell-group>
          <van-field v-model="deviceForm.imei" required clearable left-icon="imei" label="IMEI" placeholder="请输入IMEI号" />
        </van-cell-group>
        <van-button size="large" type="danger" :loading="isLoading" @click="submitBindDevice">提交绑定</van-button>

      </div>

    </van-popup>
  </div>
</template>

<script>
import { mediaURL } from "@/config";
import { mapState } from "vuex";
import wx from "weixin-js-sdk";
import { getDevices, bindDevice, unBindDevice } from "./../../api/building";
import IsEmpty from "@/components/is-empty/";
export default {
  data() {
    return {
      isLoading: false,
      addDeviceShow: false,
      shopId: 0,
      items:[],
      deviceForm: {
        imei: ""
      }
    };
  },
  computed: {
    delWidth() {
      return window.innerWidth * 0.2;
    }
  },
  watch: {},

  created() {},
  mounted() {
    this.shopId = this.$route.query.id;
    this.initData();
  },
  activated() {},

  deactivated() {},

  methods: {
    async initData() {
      let res = await getDevices({ id: this.shopId });
      if (res.code === 0) {
        this.items = res.data;
      } else {
        this.$toast.fail(res.msg);
      }
    },
    sanQRCode() {
      const vm = this;
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function(res) {
          try {
            let result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
            let IMEI = result.split("&")[0].split("=")[1];
            if (IMEI) {
              vm.deviceForm.imei = IMEI;
              vm.addDeviceShow = true;
            } else {
              vm.$toast("请扫描烟感设备二维码");
            }
          } catch (error) {
            vm.$toast("请扫描烟感设备二维码");
          }

          //   window.location.href = result; //因为我这边是扫描后有个链接，然后跳转到该页面
        }
      });
    },
    addDevice() {
      this.deviceForm.imei = "";
      this.addDeviceShow = true;
    },
    onClose(clickPosition, instance) {
      const vm = this;
      const IMEI = instance.$children[0].$children[0].value;
      switch (clickPosition) {
        case "left":
        case "cell":
        case "outside":
          instance.close();
          break;
        case "right":
          this.$dialog
            .confirm({
              message: "确定解绑？"
            })
            .then(() => {
              vm.submitUnBindDevice(IMEI);
              instance.close();
            })
            .catch(() => {
              // on cancel
            });
          break;
      }
    },
    async submitBindDevice() {
      this.isLoading = true;
      let res = await bindDevice({
        imei: this.deviceForm.imei,
        bd_id: this.shopId
      });
      if (res.code === 0) {
        this.$toast.success("设备绑定成功！");
        this.initData();
      } else {
        this.$toast.fail(res.msg);
      }
      this.isLoading = false;
    },
    async submitUnBindDevice(IMEI) {
      let res = await unBindDevice({ imei: IMEI });
      if (res.code === 0) {
        this.$toast.success("设备解绑成功！");
        this.initData();
      } else {
        this.$toast.fail(res.msg);
      }
    },
    takePic(imei) {
      const vm = this;
      wx.chooseImage({
        count: 1, //张数， 默认9
        sizeType: ["compressed"], //建议压缩图
        sourceType: ["album", "camera"], // 来源是相册、相机
        success: function(res) {
          // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          var localId = res.localIds[0];
          wx.uploadImage({
            localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function(res) {
              var serverId = res.serverId; // 返回图片的服务器端ID
              vm.uploadPic(serverId, imei);
            }
          });
        }
      });
    }
  },

  components: {
    IsEmpty
  }
};
</script>


<style lang="scss" scoped>
@import "./../../../../assets/scss/mixin";
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s;
}
.backTop {
  position: fixed;
  right: 20px;
  bottom: 80px;
  font-size: 24px;
}


.van-swipe-cell {
  &__left,
  &__right {
    color: #ffffff;
    font-size: 14px;
    height: 100%;
    display: inline-block;
    text-align: center;
    display: flex;
    align-items: center; /*垂直居中*/
    justify-content: center; /*水平居中*/
    background-color: #f44;
  }
}
.van-button__text {
  width: 100%;
}
</style>
